#include "StdAfx.h"
#include "WaveInstrumentFactory.h"
#include "audio\DirSoundSource.h"
#include <cmath>

CWaveInstrumentFactory::CWaveInstrumentFactory(void)
{
   /* for(double time=0;  time<2;  time += 1. / 44100.)
    {
        mWave.push_back(short(3267 * sin(2 * 3.1415 * 1000 * time)));
    }*/

	LoadFile(L"./sounds/jp_deep_bass_01.wav");
}


CWaveInstrumentFactory::~CWaveInstrumentFactory(void)
{
}

CWaveInstrument *CWaveInstrumentFactory::CreateInstrument( void )
{
	CWaveInstrument *lInstrument = new CWaveInstrument();
	//lInstrument->GetPlayer()->SetSamples( &mWave[0], (int)mWave.size() );
	lInstrument->GetPlayer()->SetSamples( &mWaveMap[mNextFileName].at(0), (unsigned)mWaveMap[mNextFileName].size() );

	return lInstrument;
}

void CWaveInstrumentFactory::SetNote( CNote *aNote )
{
	// Get a list of all attribute nodes and the
    // length of that list
    CComPtr<IXMLDOMNamedNodeMap> attributes;
    aNote->Node()->get_attributes(&attributes);
    long len;
    attributes->get_length(&len);

    // Loop over the list of attributes
    for(int i=0;  i<len;  i++)
    {
        // Get attribute i
        CComPtr<IXMLDOMNode> attrib;
        attributes->get_item(i, &attrib);

        // Get the name of the attribute
        CComBSTR name;
        attrib->get_nodeName(&name);

        CComVariant value;
        attrib->get_nodeValue(&value);
		if( name == "file" )
		{
			LoadFile(value.bstrVal);
			mNextFileName = value.bstrVal;
		}

    }
}

bool CWaveInstrumentFactory::LoadFile( const WCHAR *aFileName )
{
	//mWave.clear();
	
	CDirSoundSource mFile;

	//Check to see if the wav file is already stored in memory
	if( !mWaveMap[aFileName].empty() )
	{
		return true;
	}

	if( !mFile.Open( aFileName ) )
	{
		CString lMsg = L"Unable to open audio file";
        lMsg += aFileName;
        AfxMessageBox(lMsg);
        return false;
    }

	//mWave.resize(mFile.NumSampleFrames());

    for(int i=0;  i<mFile.NumSampleFrames();  i++)
    {
        short frame[2];
        mFile.ReadFrame(frame);
		mWaveMap[aFileName].push_back(frame[0]);
        //mWave.push_back(frame[0]);
    }

    mFile.Close();
    return true;
}